package com.lry.basic.redis.distributeLock;


import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
public class TestDistributeLock {

    DistributeLock lock= new DistributeLock();

    @Test
    public void testReentrant(){
        lock.lock("a");
        lock.lock("a");
    }


    @Test
    public void testWatchDog() throws InterruptedException {
        lock.lock("a");

        //锁的过期时间为30s，休眠40s，测试看门狗会不会自己延迟过期时间
        Thread.sleep(50000);

        lock.unlock("a");
    }



    static int i = 0;
    @Test
    public void testSafe() throws InterruptedException {
        TestDistributeLock test = new TestDistributeLock();
        int concurrent = 10;
        CountDownLatch cdl = new CountDownLatch(concurrent);

        List<Thread> threadList = new ArrayList<>();
        for(int i=0;i<concurrent;i++){

            Thread t = new Thread(()->{
                for(int j=0;j<1000;j++)
                    test.add();

                cdl.countDown();
            });

            threadList.add(t);
        }

        threadList.parallelStream().forEach(Thread::start);

        cdl.await();

        System.out.println(i);

    }


    private void add(){
        try{
            lock.lock("add");
            i++;
        }finally {
            lock.unlock("add");
        }
    }
}
